<?php
/**
 * phpexcel导入类.
 * 
 * @author  莫 念 
 * @version 1.0
 * @package main
 */


class Import{
	private $PHPExcel;
    private $PHPReader;
    public $error;
	 /**
     * 初始化
     * @param type $options 参数
     * @return 
     */
    public  function __construct() {
		$type = $this->config['type'];
		$driver = dirname(__FILE__).'/Driver/PHPexcel/';
		require_once($driver.'PHPExcel.php');
		require_once($driver.'PHPExcel/Reader/Excel5.php');

		$this->PHPExcel = new PHPExcel();
		$this->PHPReader = new PHPExcel_Reader_Excel2007();
       
    }

	/**
	 * 读文件
	 *
	 */
	public function read($file,$isimage = 0 ){
		if(!$file || !file_exists($file)){
			$this->error = '未找到要导入的文件';
			return false;
		}

		if(!$this->canRead($file)){   
            return false;
        }   
		
		$arr = array();

		$PHPExcel = $this->PHPReader->load($file);

		$currentSheet = $PHPExcel->getSheet(0);

		$allColumn = $currentSheet->getHighestColumn();

		//获取总行数
		$allRow=$currentSheet->getHighestRow();
		//循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
		for($currentRow = 1;$currentRow <= $allRow;$currentRow++){
			//从哪列开始，A表示第一列
			for($currentColumn = 'A';$currentColumn <= $allColumn;$currentColumn++){
				//数据坐标
				$address = $currentColumn.$currentRow;
				//读取到的数据，保存到数组$arr中
				$arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
			}
		}


		if($arr){
			$imageArr = array();
			if($isimage){
				$savePath = dirname(__FILE__).'/improt/'.date('Ymd').'/';
				if(!is_dir($savePath)){
					if(!mkdir($savePath,0777,true)){
						$this->error="目录创建失败";
						return false;
					}
				}

				$AllImages = $currentSheet->getDrawingCollection();
				foreach ( $AllImages as $drawing ) {
					$codata = $drawing->getCoordinates(); 
					$filename = $drawing->getIndexedFilename(); 
					$imageArr[$codata] = $codata.'_'.$filename.'.jpg';
					ob_start();
					call_user_func(
						$drawing->getRenderingFunction(),
						$drawing->getImageResource()
					);
					$imageContents = ob_get_contents();
					file_put_contents($savePath.$codata.'_'.$filename.'.jpg',$imageContents); //把文件保存到本地
					ob_end_clean();
				}
			}
		
			return array('data' => $arr,'image' => $imageArr);
		}

		return array();
	}

	private function canRead($file){
		if(!$this->PHPReader->canRead($file)){   
			$this->PHPReader = new \PHPExcel_Reader_Excel5();
			 if(!$this->PHPReader->canRead($file)){   
                $this->error = '无法读取该文件';
                return false;   
            }   
		}
		return true;
	
	}




}
